import { realm, schemaName } from "./schema"
import { useState, useRef, useEffect } from 'react'
import { store } from "../redux/store"


const realmValue = () => {
    const { app } = store.getState()
    const MsgLis = realm.objects(schemaName.FriendMsgLis).sorted('T', true)
    const GroupMsgLis = realm.objects(schemaName.GroupMsgLis)
    const UserInfo = realm.objects(schemaName.UserInfo)[0]
    const GroupMembers = realm.objects(schemaName.GroupMembers)
    const UserInfoList = realm.objects(schemaName.UserInfoList)
    const setUserInfo = (item) => {
        realm.write(() => {
            realm.create(schemaName.UserInfo, item, true);
        })
    }
    //设置群成员
    const setGroupMembers = ({ G, list }) => {
        realm.write(() => {
            realm.delete(GroupMembers.filtered(`G == ${G} and UserId == ${UserInfo.Id}`))
            list.map(item => realm.create(schemaName.GroupMembers, { ...item, _G_I: '_' + G + '_' + item.I, G: G, UserId: UserInfo.Id }, true))
        })
    }
    //清空加群未读
    const setGroupJoinUnread = ({ G }) => {
        const list = GroupMsgLis.filtered(`G == ${G} and MT == 61 and UserId == ${UserInfo.Id} and Unread == 1`).sorted('T', true)
        realm.write(() => {
            removeDuplicates(list, 'F').map(item => realm.create(schemaName.GroupMsgLis, { ...item, Unread: 0 }, true))
        })
    }
    //设置群信息
    const setGroupInfo = (item) => {
        realm.write(() => {
            realm.create(schemaName.GroupInfo, { ...item, UserId: UserInfo.Id }, true);
        })
    }
    //获取加群未读
    const getGroupJoinUnread = ({ G }) => {
        const list = GroupMsgLis.filtered(`G == ${G} and MT == 61 and UserId == ${UserInfo.Id} and Unread == 1`).sorted('T', true)
        return removeDuplicates(list, 'F')
    }
    //获取群成员
    const getGroupMembers = ({ G }) => {
        return GroupMembers.filtered(`G == ${G} and UserId == ${UserInfo.Id}`)
    }
    //获取加群列表
    const getGroupJoin = ({ G }) => {
        const list = GroupMsgLis.filtered(`G == ${G} and MT == 61 and UserId == ${UserInfo.Id}`).sorted('T', true)
        return removeDuplicates(list, 'F')
    }

    return {
        MsgLis,
        GroupMsgLis,
        UserInfo,
        GroupMembers,
        UserInfoList,
        setGroupInfo,
        setGroupJoinUnread,
        setGroupMembers,
        setUserInfo,
        getGroupJoinUnread,
        getGroupJoin,
        getGroupMembers
    }
};

const removeDuplicates = (list, id) => {
    const some = [];
    list.forEach(el => {
        if (!some.some(e => e[id] == el[id])) {
            some.push(el);
        }
    });
    return some
}

//导出
export default realmValue
